package edu.must.uh.util;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.ResourceBundle;
import javax.sql.DataSource;
import org.apache.log4j.Logger;


public class SqlMyDataSource implements DataSource{
    
    private static SqlMyDataSource instance = new SqlMyDataSource();
    private SqlMyDataSource() {
        
    }
    public static SqlMyDataSource getInstance() {
       
        return instance;
    }
    private static  String DriverName = "com.mysql.jdbc.Driver";
    private static  String url = "";
    private static  String username = "";
    private static  String password = "";
 //  private static  Connection conn = null;
    private static  Logger logger = Logger.getLogger(SqlMyDataSource.class);
     //定义一个池，用于存放连接
    private static LinkedList<Connection> pool = new LinkedList<Connection>();
    
    static{
        try {                         
                ResourceBundle res = ResourceBundle.getBundle("uh");
                url = res.getString("mysql.url"); 
                username = res.getString("mysql.username");  
                password = res.getString("mysql.password"); 
                DriverName = res.getString("mysql.driver"); 
                Class.forName(DriverName); 
                addConnection();              
                
                logger.info("-------------------------mysql connect successfully--------------------------"); 
       } catch (Exception e) {                
            logger.error("mysql connect fail", e);
            throw new RuntimeException("mysql connect fail");
        }
    }
    
    private static void addConnection() throws SQLException {
        pool.clear();
        for(int i = 0; i < 10; i++) {
            final Connection conn = DriverManager.getConnection(url, username, password); 
            ClassLoader classLoader = conn.getClass().getClassLoader();
            Class<?>[] interfaces =  new Class[] { Connection.class };
            Connection proxyConn = (Connection) Proxy.newProxyInstance(classLoader,interfaces ,
                    new InvocationHandler() { 
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            // TODO 自动生成的方法存根      
                            if(method.getName().equalsIgnoreCase("close")&&(args==null||args.length==0)){
                                synchronized (pool) {
                                    pool.add((Connection) proxy);//需要强转
                                    pool.notify();//唤醒等待的资源                                 
                                }
                                return null; 
                             }
                            else {
                                return  method.invoke(conn, args);                               
                            }
                          
                        }            
            });  
            pool.add((Connection)proxyConn);
           
        }
        
    }
    
    @Override
    public Connection getConnection() throws SQLException {         
        synchronized (pool) {//同步锁，一次只能一个进来拿，避免同时拿
            if(pool.size()<=0){
                try {
                    pool.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Connection conn = pool.removeFirst();
            try {
                conn.setAutoCommit(true);
            }
            catch (SQLException e) {
                logger.info("-----------------Connection lost---------------");
                addConnection();
                conn =  pool.removeFirst(); 
            }        
           return  conn; 
        }
    }
    
 // 获取池中的连接数
    public static int getPoolSize() {
        return pool.size();
    }
    

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        // TODO Auto-generated method stub
        return false;
    }


    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

  

}
